<template>
  <div id="mapView" class="map-view">
    <!-- 图层控制面板 -->
    <div class="layer-control-panel">
      <el-card class="layer-card">
        <el-collapse v-model="activeCollapse">
          <el-collapse-item title="图层显示控制" name="layers">
            <el-space direction="vertical" alignment="stretch" size="small">
              <el-checkbox
                v-model="layerVisibility.highway"
                @change="toggleLayerVisibility('highway')"
                >高速公路</el-checkbox
              >
              <el-checkbox
                v-model="layerVisibility.entryPoint"
                @change="toggleLayerVisibility('entryPoint')"
                >高速公路进入点</el-checkbox
              >
              <el-checkbox
                v-model="layerVisibility.serviceArea"
                @change="toggleLayerVisibility('serviceArea')"
                >高速公路服务区</el-checkbox
              >
            </el-space>
          </el-collapse-item>
          <el-collapse-item title="图层操作控制" name="operations">
            <el-space direction="vertical" alignment="stretch" size="small">
              <el-button type="primary" @click="startAddRoad" :disabled="isDrawing">
                <el-icon><Plus /></el-icon> 新增道路
              </el-button>
              <el-button type="primary" @click="startAddEntryPoint" :disabled="isDrawing">
                <el-icon><Plus /></el-icon> 新增高速进出口
              </el-button>
              <el-button type="primary" @click="startAddServiceArea" :disabled="isDrawing">
                <el-icon><Plus /></el-icon> 新增高速服务区
              </el-button>
            </el-space>
          </el-collapse-item>
        </el-collapse>
      </el-card>
    </div>

    <!-- 道路属性表单对话框 -->
    <el-dialog
      v-model="roadFormVisible"
      :title="formMode === 'add' ? '新增道路' : '编辑道路'"
      width="500px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form :model="roadForm" label-width="120px" :rules="roadFormRules" ref="roadFormRef">
        <el-form-item label="道路名称" prop="RoadName">
          <el-input v-model="roadForm.RoadName" placeholder="请输入道路名称"></el-input>
        </el-form-item>
        <el-form-item label="起点" prop="StartPoint">
          <el-input v-model="roadForm.StartPoint" placeholder="请输入起点"></el-input>
        </el-form-item>
        <el-form-item label="终点" prop="EndPoint">
          <el-input v-model="roadForm.EndPoint" placeholder="请输入终点"></el-input>
        </el-form-item>
        <el-form-item label="车道数" prop="LaneCount">
          <el-input-number
            v-model="roadForm.LaneCount"
            :min="1"
            :max="10"
            placeholder="请输入车道数"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="设计速度(km/h)" prop="DesignSpeed">
          <el-input-number
            v-model="roadForm.DesignSpeed"
            :min="60"
            :max="120"
            :step="10"
            placeholder="请输入设计速度"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="开通日期" prop="OpenDate">
          <el-date-picker
            v-model="roadForm.OpenDate"
            type="date"
            placeholder="请选择开通日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="行政区域" prop="AdminRegion">
          <el-input v-model="roadForm.AdminRegion" placeholder="请输入行政区域"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelRoadForm">取消</el-button>
          <el-button type="primary" @click="submitRoadForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 道路属性查看对话框 -->
    <el-dialog v-model="roadInfoVisible" title="道路信息" width="500px" :key="refReshRoadKey">
      <div v-if="selectedRoad">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="道路名称">{{
            selectedRoad.attributes.RoadName
          }}</el-descriptions-item>
          <el-descriptions-item label="起点">{{
            selectedRoad.attributes.StartPoint
          }}</el-descriptions-item>
          <el-descriptions-item label="终点">{{
            selectedRoad.attributes.EndPoint
          }}</el-descriptions-item>
          <el-descriptions-item label="车道数">{{
            selectedRoad.attributes.LaneCount
          }}</el-descriptions-item>
          <el-descriptions-item label="设计速度"
            >{{ selectedRoad.attributes.DesignSpeed }} km/h</el-descriptions-item
          >
          <el-descriptions-item label="开通日期">{{
            selectedRoad.attributes.OpenDate
          }}</el-descriptions-item>
          <el-descriptions-item label="行政区域">{{
            selectedRoad.attributes.AdminRegion
          }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="roadInfoVisible = false">关闭</el-button>
          <el-button type="primary" @click="editRoad">编辑</el-button>
          <el-button type="danger" @click="confirmDeleteRoad">删除</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 删除确认对话框 -->
    <el-dialog v-model="deleteConfirmVisible" title="确认删除" width="300px">
      <p>确定要删除该道路吗？此操作不可恢复。</p>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteConfirmVisible = false">取消</el-button>
          <el-button type="danger" @click="deleteRoad">确定删除</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 进出口点属性表单对话框 -->
    <el-dialog
      v-model="entryPointFormVisible"
      :title="formMode === 'add' ? '新增高速进出口' : '编辑高速进出口'"
      width="500px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form
        :model="entryPointForm"
        label-width="120px"
        :rules="entryPointFormRules"
        ref="entryPointFormRef"
      >
        <el-form-item label="进出口名称" prop="EntranceName">
          <el-input v-model="entryPointForm.EntranceName" placeholder="请输入进出口名称"></el-input>
        </el-form-item>
        <el-form-item label="进出口类型" prop="EntranceType">
          <el-select
            v-model="entryPointForm.EntranceType"
            placeholder="请选择进出口类型"
            style="width: 100%"
          >
            <el-option label="入口" value="入口"></el-option>
            <el-option label="出口" value="出口"></el-option>
            <el-option label="出入口" value="出入口"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属道路" prop="RoadID">
          <el-select
            v-model="entryPointForm.RoadID"
            placeholder="请选择所属道路"
            style="width: 100%"
          >
            <el-option
              v-for="road in roadList"
              :key="road.attributes.FID"
              :label="road.attributes.RoadName"
              :value="road.attributes.FID.toString()"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="方向" prop="Direction">
          <el-select
            v-model="entryPointForm.Direction"
            placeholder="请选择方向"
            style="width: 100%"
          >
            <el-option label="东向" value="东向"></el-option>
            <el-option label="南向" value="南向"></el-option>
            <el-option label="西向" value="西向"></el-option>
            <el-option label="北向" value="北向"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelEntryPointForm">取消</el-button>
          <el-button type="primary" @click="submitEntryPointForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 进出口点属性查看对话框 -->
    <el-dialog
      v-model="entryPointInfoVisible"
      title="高速进出口信息"
      width="500px"
      :key="refReshEntryPointKey"
    >
      <div v-if="selectedEntryPoint">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="进出口名称">{{
            selectedEntryPoint.attributes.EntranceName
          }}</el-descriptions-item>
          <el-descriptions-item label="进出口类型">{{
            selectedEntryPoint.attributes.EntranceType
          }}</el-descriptions-item>
          <el-descriptions-item label="所属道路">{{
            getRoadNameById(selectedEntryPoint.attributes.RoadID)
          }}</el-descriptions-item>
          <el-descriptions-item label="方向">{{
            selectedEntryPoint.attributes.Direction
          }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="entryPointInfoVisible = false">关闭</el-button>
          <el-button type="primary" @click="editEntryPoint">编辑</el-button>
          <el-button type="danger" @click="confirmDeleteEntryPoint">删除</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 删除进出口点确认对话框 -->
    <el-dialog v-model="deleteEntryPointConfirmVisible" title="确认删除" width="300px">
      <p>确定要删除该高速进出口吗？此操作不可恢复。</p>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteEntryPointConfirmVisible = false">取消</el-button>
          <el-button type="danger" @click="deleteEntryPoint">确定删除</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 服务区属性表单对话框 -->
    <el-dialog
      v-model="serviceAreaFormVisible"
      :title="formMode === 'add' ? '新增高速服务区' : '编辑高速服务区'"
      width="500px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form
        :model="serviceAreaForm"
        label-width="120px"
        :rules="serviceAreaFormRules"
        ref="serviceAreaFormRef"
      >
        <el-form-item label="服务区名称" prop="AreaName">
          <el-input v-model="serviceAreaForm.AreaName" placeholder="请输入服务区名称"></el-input>
        </el-form-item>
        <el-form-item label="服务区类型" prop="AreaType">
          <el-select
            v-model="serviceAreaForm.AreaType"
            placeholder="请选择服务区类型"
            style="width: 100%"
          >
            <el-option label="普通服务区" value="普通服务区"></el-option>
            <el-option label="综合服务区" value="综合服务区"></el-option>
            <el-option label="旅游服务区" value="旅游服务区"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属道路" prop="RoadID">
          <el-select
            v-model="serviceAreaForm.RoadID"
            placeholder="请选择所属道路"
            style="width: 100%"
          >
            <el-option
              v-for="road in roadList"
              :key="road.attributes.FID"
              :label="road.attributes.RoadName"
              :value="road.attributes.FID.toString()"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设施" prop="Facilities">
          <el-input
            v-model="serviceAreaForm.Facilities"
            type="textarea"
            placeholder="请输入服务区设施"
            :rows="3"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelServiceAreaForm">取消</el-button>
          <el-button type="primary" @click="submitServiceAreaForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 服务区属性查看对话框 -->
    <el-dialog
      v-model="serviceAreaInfoVisible"
      title="高速服务区信息"
      width="500px"
      :key="refReshServiceAreaKey"
    >
      <div v-if="selectedServiceArea">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="服务区名称">{{
            selectedServiceArea.attributes.AreaName
          }}</el-descriptions-item>
          <el-descriptions-item label="服务区类型">{{
            selectedServiceArea.attributes.AreaType
          }}</el-descriptions-item>
          <el-descriptions-item label="所属道路">{{
            getRoadNameById(selectedServiceArea.attributes.RoadID)
          }}</el-descriptions-item>
          <el-descriptions-item label="设施">{{
            selectedServiceArea.attributes.Facilities
          }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="serviceAreaInfoVisible = false">关闭</el-button>
          <el-button type="primary" @click="editServiceArea">编辑</el-button>
          <el-button type="danger" @click="confirmDeleteServiceArea">删除</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 删除服务区确认对话框 -->
    <el-dialog v-model="deleteServiceAreaConfirmVisible" title="确认删除" width="300px">
      <p>确定要删除该高速服务区吗？此操作不可恢复。</p>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteServiceAreaConfirmVisible = false">取消</el-button>
          <el-button type="danger" @click="deleteServiceArea">确定删除</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { onMounted, onUnmounted, ref, reactive, nextTick } from 'vue'
import { ElMessage, ElForm } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import Map from '@arcgis/core/Map.js'
import MapView from '@arcgis/core/views/MapView.js'
import FeatureLayer from '@arcgis/core/layers/FeatureLayer.js'
import Graphic from '@arcgis/core/Graphic.js'
import GraphicsLayer from '@arcgis/core/layers/GraphicsLayer.js'
import SketchViewModel from '@arcgis/core/widgets/Sketch/SketchViewModel.js'
import SimpleLineSymbol from '@arcgis/core/symbols/SimpleLineSymbol.js'
import SimpleMarkerSymbol from '@arcgis/core/symbols/SimpleMarkerSymbol.js'
import SimpleFillSymbol from '@arcgis/core/symbols/SimpleFillSymbol.js'
import Query from '@arcgis/core/rest/support/Query.js'
import gaodeLayer from '../utils/GaoDeBaseLayer'
import { ElCard, ElCheckbox, ElSpace } from 'element-plus'

type RoadFormType = {
  RoadName: string
  StartPoint: string
  EndPoint: string
  LaneCount: number
  DesignSpeed: number
  OpenDate: string
  AdminRegion: string
}

type EntryPointFormType = {
  EntranceName: string
  EntranceType: string
  RoadID: string
  Direction: string
}

type ServiceAreaFormType = {
  AreaName: string
  AreaType: string
  RoadID: string
  Facilities: string
}

let view: MapView | null = null
let highwayLineLayer: FeatureLayer | null = null
let highwayEntryPointLayer: FeatureLayer | null = null
let highwayServiceAreaLayer: FeatureLayer | null = null
let sketchLayer: GraphicsLayer | null = null
let sketchViewModel: SketchViewModel | null = null
let tempGraphic: Graphic | null = null

// 图层可见性控制
const layerVisibility = ref({
  highway: true,
  entryPoint: true,
  serviceArea: true,
}) as any

// 控制折叠面板的展开状态
const activeCollapse = ref(['layers', 'operations'])
// 添加一个刷新标记
const refReshRoadKey = ref(0)
const refReshEntryPointKey = ref(0)

// 表单相关
const roadFormRef = ref<InstanceType<typeof ElForm> | null>(null)
const roadFormVisible = ref(false)
const formMode = ref<'add' | 'edit'>('add')
const isDrawing = ref(false)
const roadInfoVisible = ref(false)
const deleteConfirmVisible = ref(false)
let selectedRoad: Graphic | null = null

// 进出口点表单相关
const entryPointFormRef = ref<InstanceType<typeof ElForm> | null>(null)
const entryPointFormVisible = ref(false)
const entryPointInfoVisible = ref(false)
const deleteEntryPointConfirmVisible = ref(false)
let selectedEntryPoint: Graphic | null = null

// 服务区表单相关
const serviceAreaFormRef = ref<InstanceType<typeof ElForm> | null>(null)
const serviceAreaFormVisible = ref(false)
const serviceAreaInfoVisible = ref(false)
const deleteServiceAreaConfirmVisible = ref(false)
let selectedServiceArea: Graphic | null = null
const refReshServiceAreaKey = ref(0)

// 将响应式变量改回普通变量
let roadList: Graphic[] = []

// 进出口点表单数据
const entryPointForm = reactive<EntryPointFormType>({
  EntranceName: '',
  EntranceType: '入口',
  RoadID: '',
  Direction: '东向',
})

// 服务区表单数据
const serviceAreaForm = reactive<ServiceAreaFormType>({
  AreaName: '',
  AreaType: '普通服务区',
  RoadID: '',
  Facilities: '',
})

// 进出口点表单验证规则
const entryPointFormRules = {
  EntranceName: [{ required: true, message: '请输入进出口名称', trigger: 'blur' }],
  EntranceType: [{ required: true, message: '请选择进出口类型', trigger: 'blur' }],
  RoadID: [{ required: true, message: '请选择所属道路', trigger: 'blur' }],
  Direction: [{ required: true, message: '请选择方向', trigger: 'blur' }],
}

// 服务区表单验证规则
const serviceAreaFormRules = {
  AreaName: [{ required: true, message: '请输入服务区名称', trigger: 'blur' }],
  AreaType: [{ required: true, message: '请选择服务区类型', trigger: 'blur' }],
  RoadID: [{ required: true, message: '请选择所属道路', trigger: 'blur' }],
  Facilities: [{ required: true, message: '请输入服务区设施', trigger: 'blur' }],
}

// 开始添加高速进出口
const startAddEntryPoint = () => {
  if (!view || !sketchViewModel) return

  isDrawing.value = true
  ElMessage.info('请在地图上点击添加高速进出口位置')

  // 开始绘制点
  sketchViewModel.create('point')
}

// 开始添加服务区
const startAddServiceArea = () => {
  if (!view || !sketchViewModel) return

  isDrawing.value = true
  ElMessage.info('请在地图上点击添加高速服务区位置')

  // 开始绘制点
  sketchViewModel.create('polygon')
}

// 取消进出口点表单
const cancelEntryPointForm = () => {
  entryPointFormVisible.value = false
  resetEntryPointForm()

  // 如果是添加模式，清除临时图形
  if (formMode.value === 'add' && tempGraphic && sketchLayer) {
    sketchLayer.remove(tempGraphic)
    tempGraphic = null
  }
}

// 取消服务区表单
const cancelServiceAreaForm = () => {
  serviceAreaFormVisible.value = false
  resetServiceAreaForm()

  // 如果是添加模式，清除临时图形
  if (formMode.value === 'add' && tempGraphic && sketchLayer) {
    sketchLayer.remove(tempGraphic)
    tempGraphic = null
  }
}

// 重置进出口点表单
const resetEntryPointForm = () => {
  if (entryPointFormRef.value) {
    entryPointFormRef.value.resetFields()
  }

  entryPointForm.EntranceName = ''
  entryPointForm.EntranceType = '入口'
  entryPointForm.RoadID = ''
  entryPointForm.Direction = '东向'
}

// 重置服务区表单
const resetServiceAreaForm = () => {
  if (serviceAreaFormRef.value) {
    serviceAreaFormRef.value.resetFields()
  }

  serviceAreaForm.AreaName = ''
  serviceAreaForm.AreaType = '普通服务区'
  serviceAreaForm.RoadID = ''
  serviceAreaForm.Facilities = ''
}

// 提交进出口点表单
const submitEntryPointForm = async () => {
  if (!entryPointFormRef.value) return

  await entryPointFormRef.value.validate(async (valid) => {
    if (valid) {
      if (formMode.value === 'add') {
        // 添加新进出口点
        addEntryPoint()
      } else {
        // 更新进出口点
        updateEntryPoint()
      }
    }
  })
}

// 提交服务区表单
const submitServiceAreaForm = async () => {
  if (!serviceAreaFormRef.value) return

  await serviceAreaFormRef.value.validate(async (valid) => {
    if (valid) {
      if (formMode.value === 'add') {
        // 添加新服务区
        addServiceArea()
      } else {
        // 更新服务区
        updateServiceArea()
      }
    }
  })
}

// 添加新进出口点
const addEntryPoint = () => {
  if (!tempGraphic || !highwayEntryPointLayer) return

  // 创建新的进出口点图形
  const attributes = {
    EntranceName: entryPointForm.EntranceName,
    EntranceType: entryPointForm.EntranceType,
    RoadID: entryPointForm.RoadID,
    Direction: entryPointForm.Direction,
  }

  // 创建新的图形
  const newGraphic = new Graphic({
    geometry: tempGraphic.geometry,
    attributes: attributes,
  })

  // 添加到图层
  highwayEntryPointLayer
    .applyEdits({
      addFeatures: [newGraphic],
    })
    .then((result) => {
      if (result.addFeatureResults.length > 0) {
        ElMessage.success('高速进出口添加成功')
        entryPointFormVisible.value = false
        resetEntryPointForm()

        // 清除临时图形
        if (sketchLayer && tempGraphic) {
          sketchLayer.remove(tempGraphic)
          tempGraphic = null
        }
      } else {
        ElMessage.error('高速进出口添加失败')
      }
    })
    .catch((error) => {
      console.error('添加高速进出口出错:', error)
      ElMessage.error('高速进出口添加失败')
    })
}

// 添加新服务区
const addServiceArea = () => {
  if (!tempGraphic || !highwayServiceAreaLayer) return

  // 创建新的服务区图形
  const attributes = {
    AreaName: serviceAreaForm.AreaName,
    AreaType: serviceAreaForm.AreaType,
    RoadID: serviceAreaForm.RoadID,
    Facilities: serviceAreaForm.Facilities,
  }

  // 创建新的图形
  const newGraphic = new Graphic({
    geometry: tempGraphic.geometry,
    attributes: attributes,
  })
  // 清除临时图形
  if (sketchLayer && tempGraphic) {
    sketchLayer.remove(tempGraphic)
    tempGraphic = null
  }

  // 添加到图层
  highwayServiceAreaLayer
    .applyEdits({
      addFeatures: [newGraphic],
    })
    .then((result) => {
      if (result.addFeatureResults.length > 0) {
        ElMessage.success('高速服务区添加成功')
        serviceAreaFormVisible.value = false
        resetServiceAreaForm()

        // 清除临时图形
        if (sketchLayer && tempGraphic) {
          sketchLayer.remove(tempGraphic)
          tempGraphic = null
        }
      } else {
        ElMessage.error('高速服务区添加失败')
      }
    })
    .catch((error) => {
      console.error('添加高速服务区出错:', error)
      ElMessage.error('高速服务区添加失败')
    })
}

// 编辑进出口点
const editEntryPoint = () => {
  if (!selectedEntryPoint) return

  formMode.value = 'edit'

  // 填充表单数据
  const attrs = selectedEntryPoint.attributes
  entryPointForm.EntranceName = attrs.EntranceName || ''
  entryPointForm.EntranceType = attrs.EntranceType || '入口'
  entryPointForm.RoadID = attrs.RoadID ? attrs.RoadID.toString() : ''
  entryPointForm.Direction = attrs.Direction || '东向'

  entryPointInfoVisible.value = false
  entryPointFormVisible.value = true
}

// 编辑服务区
const editServiceArea = () => {
  if (!selectedServiceArea) return

  formMode.value = 'edit'

  // 填充表单数据
  const attrs = selectedServiceArea.attributes
  serviceAreaForm.AreaName = attrs.AreaName || ''
  serviceAreaForm.AreaType = attrs.AreaType || '普通服务区'
  serviceAreaForm.RoadID = attrs.RoadID ? attrs.RoadID.toString() : ''
  serviceAreaForm.Facilities = attrs.Facilities || ''

  serviceAreaInfoVisible.value = false
  serviceAreaFormVisible.value = true
}

// 更新进出口点
const updateEntryPoint = () => {
  if (!selectedEntryPoint || !highwayEntryPointLayer) return

  // 更新属性
  const updatedGraphic = selectedEntryPoint.clone()
  updatedGraphic.attributes.EntranceName = entryPointForm.EntranceName
  updatedGraphic.attributes.EntranceType = entryPointForm.EntranceType
  updatedGraphic.attributes.RoadID = entryPointForm.RoadID
  updatedGraphic.attributes.Direction = entryPointForm.Direction

  // 应用编辑
  highwayEntryPointLayer
    .applyEdits({
      updateFeatures: [updatedGraphic],
    })
    .then((result) => {
      if (result.updateFeatureResults.length > 0) {
        ElMessage.success('高速进出口更新成功')
        entryPointFormVisible.value = false
        resetEntryPointForm()
        // 强制刷新组件
        nextTick(() => {
          refReshEntryPointKey.value++
        })
      } else {
        ElMessage.error('高速进出口更新失败')
      }
    })
    .catch((error) => {
      console.error('更新高速进出口出错:', error)
      ElMessage.error('高速进出口更新失败')
    })
}

// 更新服务区
const updateServiceArea = () => {
  if (!selectedServiceArea || !highwayServiceAreaLayer) return

  // 更新属性
  const updatedGraphic = selectedServiceArea.clone()
  updatedGraphic.attributes.AreaName = serviceAreaForm.AreaName
  updatedGraphic.attributes.AreaType = serviceAreaForm.AreaType
  updatedGraphic.attributes.RoadID = serviceAreaForm.RoadID
  updatedGraphic.attributes.Facilities = serviceAreaForm.Facilities

  // 应用编辑
  highwayServiceAreaLayer
    .applyEdits({
      updateFeatures: [updatedGraphic],
    })
    .then((result) => {
      if (result.updateFeatureResults.length > 0) {
        ElMessage.success('高速服务区更新成功')
        serviceAreaFormVisible.value = false
        resetServiceAreaForm()
        // 强制刷新组件
        nextTick(() => {
          refReshServiceAreaKey.value++
        })
      } else {
        ElMessage.error('高速服务区更新失败')
      }
    })
    .catch((error) => {
      console.error('更新高速服务区出错:', error)
      ElMessage.error('高速服务区更新失败')
    })
}

// 确认删除进出口点
const confirmDeleteEntryPoint = () => {
  entryPointInfoVisible.value = false
  deleteEntryPointConfirmVisible.value = true
}

// 确认删除服务区
const confirmDeleteServiceArea = () => {
  serviceAreaInfoVisible.value = false
  deleteServiceAreaConfirmVisible.value = true
}

// 删除进出口点
const deleteEntryPoint = () => {
  if (!selectedEntryPoint || !highwayEntryPointLayer) return

  highwayEntryPointLayer
    .applyEdits({
      deleteFeatures: [selectedEntryPoint],
    })
    .then((result) => {
      if (result.deleteFeatureResults.length > 0) {
        ElMessage.success('高速进出口删除成功')
        deleteEntryPointConfirmVisible.value = false
      } else {
        ElMessage.error('高速进出口删除失败')
      }
    })
    .catch((error) => {
      console.error('删除高速进出口出错:', error)
      ElMessage.error('高速进出口删除失败')
    })
}

// 删除服务区
const deleteServiceArea = () => {
  if (!selectedServiceArea || !highwayServiceAreaLayer) return

  highwayServiceAreaLayer
    .applyEdits({
      deleteFeatures: [selectedServiceArea],
    })
    .then((result) => {
      if (result.deleteFeatureResults.length > 0) {
        ElMessage.success('高速服务区删除成功')
        deleteServiceAreaConfirmVisible.value = false
      } else {
        ElMessage.error('高速服务区删除失败')
      }
    })
    .catch((error) => {
      console.error('删除高速服务区出错:', error)
      ElMessage.error('高速服务区删除失败')
    })
}

// 根据道路ID获取道路名称
const getRoadNameById = (roadId: string | number) => {
  if (!roadId) return '未知道路'

  // 移除非空断言，使用可选链和空值合并操作符
  const road = roadList.find((road) => road.attributes.FID.toString() === roadId.toString())
  return road ? road.attributes.RoadName : '未知道路'
}

// 道路表单数据
const roadForm = reactive<RoadFormType>({
  RoadName: '',
  StartPoint: '',
  EndPoint: '',
  LaneCount: 4,
  DesignSpeed: 100,
  OpenDate: '',
  AdminRegion: '',
})

// 表单验证规则
const roadFormRules = {
  RoadName: [{ required: true, message: '请输入道路名称', trigger: 'blur' }],
  StartPoint: [{ required: true, message: '请输入起点', trigger: 'blur' }],
  EndPoint: [{ required: true, message: '请输入终点', trigger: 'blur' }],
  LaneCount: [{ required: true, message: '请输入车道数', trigger: 'blur' }],
  DesignSpeed: [{ required: true, message: '请输入设计速度', trigger: 'blur' }],
  OpenDate: [{ required: true, message: '请选择开通日期', trigger: 'blur' }],
  AdminRegion: [{ required: true, message: '请输入行政区域', trigger: 'blur' }],
}

// 切换图层可见性
const toggleLayerVisibility = (layerType: string) => {
  switch (layerType) {
    case 'highway':
      if (highwayLineLayer) {
        highwayLineLayer.visible = Boolean(layerVisibility.value.highway)
      }
      break
    case 'entryPoint':
      if (highwayEntryPointLayer) {
        highwayEntryPointLayer.visible = Boolean(layerVisibility.value.entryPoint)
      }
      break
    case 'serviceArea':
      if (highwayServiceAreaLayer) {
        highwayServiceAreaLayer.visible = Boolean(layerVisibility.value.serviceArea)
      }
      break
  }
}

// 开始添加道路
const startAddRoad = () => {
  if (!view || !sketchViewModel) return

  isDrawing.value = true
  ElMessage.info('请在地图上绘制道路线路')

  // 开始绘制线
  sketchViewModel.create('polyline')
}

// 取消道路表单
const cancelRoadForm = () => {
  roadFormVisible.value = false
  resetForm()

  // 如果是添加模式，清除临时图形
  if (formMode.value === 'add' && tempGraphic && sketchLayer) {
    sketchLayer.remove(tempGraphic)
    tempGraphic = null
  }
}

// 重置表单
const resetForm = () => {
  if (roadFormRef.value) {
    roadFormRef.value.resetFields()
  }

  roadForm.RoadName = ''
  roadForm.StartPoint = ''
  roadForm.EndPoint = ''
  roadForm.LaneCount = 4
  roadForm.DesignSpeed = 100
  roadForm.OpenDate = ''
  roadForm.AdminRegion = ''
}

// 提交道路表单
const submitRoadForm = async () => {
  if (!roadFormRef.value) return

  await roadFormRef.value.validate(async (valid) => {
    if (valid) {
      if (formMode.value === 'add') {
        // 添加新道路
        addRoad()
      } else {
        // 更新道路
        updateRoad()
      }
    }
  })
}

// 添加新道路
const addRoad = () => {
  if (!tempGraphic || !highwayLineLayer) return

  // 创建新的道路图形
  const attributes = {
    RoadName: roadForm.RoadName,
    StartPoint: roadForm.StartPoint,
    EndPoint: roadForm.EndPoint,
    LaneCount: roadForm.LaneCount,
    DesignSpeed: roadForm.DesignSpeed,
    OpenDate: roadForm.OpenDate,
    AdminRegion: roadForm.AdminRegion,
  }

  // 创建新的图形
  const newGraphic = new Graphic({
    geometry: tempGraphic.geometry,
    attributes: attributes,
  })

  // 添加到图层
  highwayLineLayer
    .applyEdits({
      addFeatures: [newGraphic],
    })
    .then((result) => {
      if (result.addFeatureResults.length > 0) {
        ElMessage.success('道路添加成功')
        roadFormVisible.value = false
        resetForm()

        // 清除临时图形
        if (sketchLayer && tempGraphic) {
          sketchLayer.remove(tempGraphic)
          tempGraphic = null
        }
      } else {
        ElMessage.error('道路添加失败')
      }
    })
    .catch((error) => {
      console.error('添加道路出错:', error)
      ElMessage.error('道路添加失败')
    })
}

// 编辑道路
const editRoad = () => {
  if (!selectedRoad) return

  formMode.value = 'edit'

  // 填充表单数据
  const attrs = selectedRoad.attributes
  roadForm.RoadName = attrs.RoadName || ''
  roadForm.StartPoint = attrs.StartPoint || ''
  roadForm.EndPoint = attrs.EndPoint || ''
  roadForm.LaneCount = attrs.LaneCount || 4
  roadForm.DesignSpeed = attrs.DesignSpeed || 100
  roadForm.OpenDate = attrs.OpenDate || ''
  roadForm.AdminRegion = attrs.AdminRegion || ''

  roadInfoVisible.value = false
  roadFormVisible.value = true
}

// 更新道路
const updateRoad = () => {
  if (!selectedRoad || !highwayLineLayer) return

  // 更新属性
  const updatedGraphic = selectedRoad.clone()
  updatedGraphic.attributes.RoadName = roadForm.RoadName
  updatedGraphic.attributes.StartPoint = roadForm.StartPoint
  updatedGraphic.attributes.EndPoint = roadForm.EndPoint
  updatedGraphic.attributes.LaneCount = roadForm.LaneCount
  updatedGraphic.attributes.DesignSpeed = roadForm.DesignSpeed
  updatedGraphic.attributes.OpenDate = roadForm.OpenDate
  updatedGraphic.attributes.AdminRegion = roadForm.AdminRegion

  // 应用编辑
  highwayLineLayer
    .applyEdits({
      updateFeatures: [updatedGraphic],
    })
    .then((result) => {
      if (result.updateFeatureResults.length > 0) {
        ElMessage.success('道路更新成功')
        roadFormVisible.value = false
        nextTick(() => {
          refReshRoadKey.value++
        })
        resetForm()
      } else {
        ElMessage.error('道路更新失败')
      }
    })
    .catch((error) => {
      console.error('更新道路出错:', error)
      ElMessage.error('道路更新失败')
    })
}

// 确认删除道路
const confirmDeleteRoad = () => {
  roadInfoVisible.value = false
  deleteConfirmVisible.value = true
}

// 删除道路
const deleteRoad = () => {
  if (!selectedRoad || !highwayLineLayer) return

  highwayLineLayer
    .applyEdits({
      deleteFeatures: [selectedRoad],
    })
    .then((result) => {
      if (result.deleteFeatureResults.length > 0) {
        ElMessage.success('道路删除成功')
        deleteConfirmVisible.value = false
      } else {
        ElMessage.error('道路删除失败')
      }
    })
    .catch((error) => {
      console.error('删除道路出错:', error)
      ElMessage.error('道路删除失败')
    })
}

// 初始化地图
onMounted(() => {
  // 创建高速公路线图层
  highwayLineLayer = new FeatureLayer({
    url: 'https://services6.arcgis.com/aSAH0FbO8tv30xLs/arcgis/rest/services/HighwayManagementSystem/FeatureServer/3',
    title: '高速公路',
    visible: Boolean(layerVisibility.value.highway),
    outFields: ['*'], // 确保所有字段都可用
    popupEnabled: false, // 禁用默认弹出窗口，使用自定义弹窗
  })

  // 创建高速公路进入点图层
  highwayEntryPointLayer = new FeatureLayer({
    url: 'https://services6.arcgis.com/aSAH0FbO8tv30xLs/arcgis/rest/services/HighwayManagementSystem/FeatureServer/0',
    title: '高速公路进入点',
    visible: Boolean(layerVisibility.value.entryPoint),
  })

  // 创建高速公路服务区图层
  highwayServiceAreaLayer = new FeatureLayer({
    url: 'https://services6.arcgis.com/aSAH0FbO8tv30xLs/arcgis/rest/services/HighwayManagementSystem/FeatureServer/1',
    title: '高速公路服务区',
    visible: Boolean(layerVisibility.value.serviceArea),
  })

  // 创建草图图层
  sketchLayer = new GraphicsLayer({
    title: '绘图图层',
  })

  // 创建地图实例
  const map = new Map({
    basemap: {
      baseLayers: [gaodeLayer],
    },
    layers: [highwayLineLayer, highwayEntryPointLayer, highwayServiceAreaLayer, sketchLayer], // 添加图层到地图
  })

  // 创建地图视图
  view = new MapView({
    container: 'mapView',
    map: map,
    zoom: 10,
    center: [116.7461293, 36.5598627], // 默认中心点（北京）
  })

  // 初始化绘图工具
  sketchViewModel = new SketchViewModel({
    view: view,
    layer: sketchLayer,
    defaultCreateOptions: {
      mode: 'click', // 使用点击模式创建线
    },
  })

  // 监听绘图完成事件
  sketchViewModel.on('create', (event) => {
    if (event.state === 'complete') {
      isDrawing.value = false

      // 保存临时图形
      if (event.tool === 'polyline') {
        // 道路线绘制完成
        tempGraphic = new Graphic({
          geometry: event.graphic.geometry,
          symbol: new SimpleLineSymbol({
            color: [0, 0, 255, 0.8],
            width: 4,
          }),
        })

        // 添加到草图图层
        sketchLayer?.add(tempGraphic)

        // 显示道路表单
        formMode.value = 'add'
        roadFormVisible.value = true
      } else if (event.tool === 'point') {
        // 点绘制完成
        tempGraphic = new Graphic({
          geometry: event.graphic.geometry,
          symbol: new SimpleMarkerSymbol({
            color: [255, 0, 0, 0.8],
            size: 12,
            outline: {
              color: [255, 255, 255],
              width: 1,
            },
          }),
        })
        // 添加到草图图层
        sketchLayer?.add(tempGraphic)
        // 加载道路列表
        loadRoadList()
        // 根据当前操作判断显示哪个表单
        formMode.value = 'add'
        // 添加进出口点
        entryPointFormVisible.value = true
      } else if (event.tool === 'polygon') {
        // 面绘制完成
        tempGraphic = new Graphic({
          geometry: event.graphic.geometry,
          symbol: new SimpleFillSymbol({
            color: [0, 0, 255, 0.8],
            outline: {
              color: [255, 255, 255],
              width: 1,
            },
          }),
        })
        // 添加到草图图层
        sketchLayer?.add(tempGraphic)
        // 加载道路列表
        loadRoadList()
        // 根据当前操作判断显示哪个表单
        formMode.value = 'add'
        // 如果是添加服务区
        serviceAreaFormVisible.value = true
      }
    }
  })

  // 监听点击事件，用于查询道路和进出口点信息
  view.on('click', async function (event) {
    // 如果正在绘制，不执行查询
    if (isDrawing.value) return

    // 转换空间参考
    const mapPoint = event.mapPoint
    // 创建查询对象
    const query = new Query()
    query.geometry = mapPoint
    query.distance = 0.1
    query.units = 'miles'
    query.spatialRelationship = 'intersects'
    query.returnGeometry = true
    query.outFields = ['*']

    try {
      // 先查询高速服务区图层
      if (highwayServiceAreaLayer && highwayServiceAreaLayer.visible) {
        // 强制刷新图层
        highwayServiceAreaLayer.refresh()
        const serviceAreaResult = await highwayServiceAreaLayer.queryFeatures(query)
        if (serviceAreaResult.features.length > 0) {
          // 找到服务区，显示信息
          selectedServiceArea = serviceAreaResult.features[0]
          serviceAreaInfoVisible.value = true
          return
        }
      }

      // 再查询高速进出口点图层
      if (highwayEntryPointLayer && highwayEntryPointLayer.visible) {
        // 强制刷新图层
        highwayEntryPointLayer.refresh()
        const entryPointResult = await highwayEntryPointLayer.queryFeatures(query)
        if (entryPointResult.features.length > 0) {
          // 找到进出口点，显示信息
          selectedEntryPoint = entryPointResult.features[0]
          entryPointInfoVisible.value = true
          return
        }
      }

      // 如果没有找到进出口点，查询道路图层
      if (highwayLineLayer && highwayLineLayer.visible) {
        // 强制刷新图层
        highwayLineLayer.refresh()
        const roadResult = await highwayLineLayer.queryFeatures(query)
        if (roadResult.features.length > 0) {
          // 找到道路，显示信息
          selectedRoad = roadResult.features[0]
          roadInfoVisible.value = true
          return
        }
      }

      // 如果都没有找到，可以添加其他图层的查询
      console.log('点击位置没有找到要素')
    } catch (error) {
      console.error('查询要素出错:', error)
      ElMessage.error('查询要素失败')
    }
  })

  // 加载道路列表
  loadRoadList()
})

// 加载道路列表
const loadRoadList = () => {
  if (!highwayLineLayer) return

  // 查询所有道路
  const query = highwayLineLayer.createQuery()
  query.outFields = ['FID', 'RoadName']
  query.returnGeometry = false

  highwayLineLayer
    .queryFeatures(query)
    .then((results) => {
      if (results.features && results.features.length > 0) {
        // 直接赋值给普通变量，不再使用 .value
        roadList = results.features
      }
    })
    .catch((error) => {
      console.error('加载道路列表出错:', error)
      ElMessage.error('加载道路列表失败')
    })
}

// 组件卸载时清理资源
onUnmounted(() => {
  if (sketchViewModel) {
    sketchViewModel = null
  }

  if (view) {
    view = null
  }
})
</script>

<style scoped>
.map-view {
  width: 100%;
  height: 100%;
  position: relative;
}

.layer-control-panel {
  position: absolute;
  top: 20px;
  right: 20px;
  z-index: 10;
}

.layer-card {
  width: 220px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}
</style>
